package org.linphone.activity;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.linphone.LinphoneService;
import com.leehuubsd.yiyanzb.R;
import com.umeng.analytics.MobclickAgent;

import org.linphone.Bean.LandedDate;
import org.linphone.Server.PhoneReceiver;
import org.linphone.setup.SetupActivity;
import org.linphone.util.ContactTest;
import org.linphone.yinpin.CallPhoneHeHe;
import org.linphone.yinpin.CallPhoneYinPin;
import org.linphone.yinpin.IXinTempStorage;
import org.linphone.yinpin.ScrollPositionDotView;
import org.linphone.yinpin.ViewFlipperWrapper;
import org.linphone.yinpin.ViewFlipperWrapper.OnNextShowListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Paint;
import android.graphics.drawable.AnimationDrawable;
//import android.hardware.Sensor;
//import android.hardware.SensorEvent;
//import android.hardware.SensorEventListener;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.CallLog;
import android.provider.ContactsContract.Data;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

public class CallPhoneActivity extends Activity implements
// SensorEventListener,
		OnNextShowListener {

	private TextView mZT;
	private SharedPreferences sharedPreferences;
	private CallPhoneYinPin iXinCallPhoneYinPin;
	private AudioManager audioManager;
	// private SensorManager mSensorManager;
	// private Sensor mSensor;
	private ImageView image;
	private ViewFlipperWrapper mCallAdFlipper;
	private String OEMID, http;
	private ScrollPositionDotView mDotView;
	private Handler mHandleR = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 69:
				String ss = (String) msg.obj;
				if (ss != null) {
					String[] split = ss.split("[|]");
					char c = ss.charAt(2);
					String str = String.valueOf(c);
					System.out.println(str);
					Toast.makeText(getApplicationContext(), str, 1).show();
					try {

						if ('e' == ss.charAt(2)) {
							// mZT.setText(R.string.call_waitting_info);
							if (mWifiLock.isHeld()) {
								mWifiLock.acquire();
							}
						} else {
							// mZT.setText(split[2]);
							if (mWifiLock.isHeld()) {
								mWifiLock.acquire();
							}
						}

					} catch (Exception e) {
						// TODO: handle exception
					}
				}
				break;
			}
			super.handleMessage(msg);
		}
	};

	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		try {
			this.finish();
			if (b) {
				mp.stop();
				audioManager.setMode(AudioManager.MODE_NORMAL);
			}
			unregisterReceiver(myReceiver2);

		} catch (Exception e) {
			// TODO: handle exception
		}
		super.onPause();
		MobclickAgent.onPause(this);
		try {
			long oldtime = sharedPreferences.getLong("getGapCount", 0);
			SharedPreferences sharedPreferencesaa = getSharedPreferences(
					"bosidengaa", Context.MODE_WORLD_READABLE);
			Editor editaa = sharedPreferences.edit();
			long rawContactId = sharedPreferencesaa.getLong("rawContactId", 0);
			Date date1 = new Date();
			long times1 = date1.getTime();
			boolean queryNameInfob = true;
			try {
				queryNameInfob = queryNameInfo(this, rawContactId + "");
			} catch (Exception e) {
				// TODO: handle exception
				queryNameInfob = false;
			}
			if (rawContactId == 0 || getGapCount(oldtime) >= 15
					|| queryNameInfob) {
				ContactTest test = new ContactTest();
				test.PostDate(this, cardno, passWord);
				Date date = new Date();
				long times = date.getTime();
				editaa.putLong("getGapCount", times);
				editaa.commit();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	private MediaPlayer mp;
	private String phoneNum, phoneName;
	private TextView tv1, phonen;
	private Boolean b;
	private static final int WIZARD_INTENT = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		OEMID = getResources().getString(R.string.oem);
		http = getResources().getString(R.string.http);
		if (!getLandName()) {
			Intent intent = new Intent(LinphoneService.instance(), SetupActivity.class);
			startActivityForResult(intent, WIZARD_INTENT);
			finish();
		}
		new Thread(new CheckVersionUpdate()).start();
		Intent intent = getIntent();
		sharedPreferences = getSharedPreferences("bosideng",
				Context.MODE_WORLD_READABLE);
		b = sharedPreferences.getBoolean("i9300", true);
		try {
			phoneNum = intent.getStringExtra("CALLNUMBER");
			phoneName = intent.getStringExtra("CALLNAME");
		} catch (Exception e) {
			phoneNum = intent.getStringExtra("CALLNUMBER");
			phoneName = intent.getStringExtra("CALLNAME");
		}
		if (phoneNum.length() != 5) {
			if (phoneNum.length() > 4 && phoneNum.substring(0, 3).equals("400")) {
				Toast.makeText(this, "不支持拨打400号码", 0).show();
				finish();
			} else if (phoneNum.length() < 10) {
				Toast.makeText(this, "号码错误，拨打固话请加区号", 0).show();
				finish();
			} else {
				iXinCallPhoneYinPin = new CallPhoneYinPin(this);
				if (b) {
					mp = iXinCallPhoneYinPin.getMp();
					audioManager = (AudioManager) this
							.getSystemService(Context.AUDIO_SERVICE);
					if (audioManager != null) {
						audioManager.setMode(AudioManager.MODE_IN_CALL);
						try {
							mp.start();
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				}
				CallPhoneHeHe iXinCallPhoneHeHe = CallPhoneHeHe
						.getIXinCallPhoneHeHe();
				iXinCallPhoneHeHe.setCallPhoneYinPin(iXinCallPhoneYinPin);
				requestWindowFeature(Window.FEATURE_NO_TITLE);
				setContentView(R.layout.activity_call_phone);
				init();
				tv1 = (TextView) findViewById(R.id.call_tv);
				tv1.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);// 下划线
				tv1.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Intent intent3 = new Intent(CallPhoneActivity.this,
								WebsiteActivity.class);
						intent3.putExtra("pathweb",
								"http://faqbosideng.leehuu.cn/index-common.html");
						intent3.putExtra("title", "常见问题");
						startActivity(intent3);
					}
				});
				try {
					image = (ImageView) findViewById(R.id.ImgDance11);
					image.setBackgroundResource(R.anim.calling_b);
					AnimationDrawable anim = (AnimationDrawable) image.getBackground();
					anim.start();
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		} else {
			Toast.makeText(this, "不能拨打服务号码", 0).show();
			finish();
		}
	}

	private String passWord, cardno;

	private boolean getLandName() {
		LandedDate landedDate = new LandedDate(this);
		passWord = landedDate.getCardPassword();
		cardno = landedDate.getPhone();
		String cardno = landedDate.getCardNo();
		if (passWord == null ||
		// phone == null||
				cardno == null) {
			return false;
		}
		return true;
	}

	public void showTopWindow(View paramView) {
		WindowManager localWindowManager = (WindowManager) getApplicationContext()
				.getSystemService("window");
		WindowManager.LayoutParams localLayoutParams = new WindowManager.LayoutParams();
		localLayoutParams.type = 2007;
		localLayoutParams.width = -1;
		localLayoutParams.height = -1;
		localLayoutParams.x = 0;
		localLayoutParams.y = 0;
		localWindowManager.addView(paramView, localLayoutParams);
	}

	private TextView tvPhoneName;
	private TextView tvPhoneNum;
	private IXinTempStorage iXinTempStorage = IXinTempStorage
			.getIXinTempStorage();

	private void init() {
		tvPhoneName = (TextView) findViewById(R.id.textViewId_phoneName_callingPhone);
		tvPhoneNum = (TextView) findViewById(R.id.textViewId_phoneNum_callingPhone);
		ContentResolver resolver = getContentResolver();

		if (resolver != null) {
			ContentValues values = new ContentValues();
			values.put(CallLog.Calls.NUMBER, phoneNum);
			values.put(CallLog.Calls.CACHED_NAME, phoneName);
			values.put(CallLog.Calls.TYPE, CallLog.Calls.OUTGOING_TYPE);
			values.put(CallLog.Calls.DATE, System.currentTimeMillis());
			try {

				resolver.insert(CallLog.Calls.CONTENT_URI, values);// 空指针异常
			} catch (Exception e) {
				// TODO: handle exception
			}
		}

		tvPhoneName.setText(phoneName);
		tvPhoneNum.setText(phoneNum);
		IXinTempStorage iXinTempStorage = IXinTempStorage.getIXinTempStorage();
		// iXinTempStorage.setView(mView);
		mZT = (TextView) findViewById(R.id.textViewId_ZT_CallingPhone);
		mZT.setText(R.string.call_waitting_info);
		StringBuffer sb = new StringBuffer(phoneNum);
		String namees = sharedPreferences.getString("Phone", null);
		String CardNo = sharedPreferences.getString("CardNo", null);
		String CardPassWord = sharedPreferences.getString("CardPassWord", null);
		TextView p = (TextView) findViewById(R.id.t1);
		p.setText(namees);

		mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		mWifiLock = mWifiManager.createWifiLock("Test");
		if (mWifiLock != null) {
			try {
				mWifiLock.acquire();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		postDataToNe("/YXBp/dm9zb2Vt/TWFrZUNhbGxCYWNr", CardPassWord, namees,
				phoneNum);

		List<View> list = new ArrayList<View>();
		ImageView fhh = (ImageView) findViewById(R.id.imageButtonId_FHH_CallingPhone);
		fhh.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				CallPhoneActivity.this.finish();
				try {

					if (b) {
						MediaPlayer mp = iXinCallPhoneYinPin.getMp();
						if (mp != null) {
							mp.stop();
							audioManager.setMode(AudioManager.MODE_NORMAL);
						}
					}

					String[] projection = { CallLog.Calls.DATE,
							CallLog.Calls.NUMBER, CallLog.Calls.TYPE,
							CallLog.Calls.CACHED_NAME, CallLog.Calls._ID };
					Cursor cursor = getContentResolver().query(
							CallLog.Calls.CONTENT_URI, projection, null, null,
							null);
					ContentResolver resolver = getContentResolver();
					if (cursor != null && resolver != null) {
						cursor.moveToFirst();
						while (cursor.moveToNext()) {
							String number = cursor.getString(cursor
									.getColumnIndex(CallLog.Calls.NUMBER));
							int id = cursor.getInt(cursor
									.getColumnIndex(CallLog.Calls._ID));
							if ("-1".equals(number) || "-2".equals(number)
									|| "".equals(number) || number == null) {
								resolver.delete(CallLog.Calls.CONTENT_URI,
										CallLog.Calls._ID + "=?",
										new String[] { id + "" });
							}
						}
					}

				} catch (Exception e) {
					// TODO: handle exception
				}
				finish();
			}
		});

		String phoneNamea = android.os.Build.MODEL;
		if (phoneNamea != null && !"M040".equals(phoneNamea)
				&& !android.os.Build.BRAND.equals("Meizu")) {
			myReceiver2 = new PhoneReceiver();
			intentFilter = new IntentFilter("android.intent.action.PHONE_STATE");
			registerReceiver(myReceiver2, intentFilter);
		} else {
			Toast.makeText(this, R.string.call_autolisten_unsupport_toast,
					Toast.LENGTH_SHORT).show();
		}

	}

	private class CheckVersionUpdate implements Runnable {
		@Override
		public void run() {
			try {
				Thread.sleep(30000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			finish();
		}
	}


	public void parserToObject(String json) {
		try {
			JSONTokener jsonTokener = new JSONTokener(json);
			JSONObject object = (JSONObject) jsonTokener.nextValue();
			int i = object.getInt("retCode");
			if (i == 0) {
				mZT.setText("呼叫成功");
			} else {
				mZT.setText("呼叫失败");
				String s = object.getString("exception");
				Toast.makeText(getApplicationContext(),
						s + "(" + object.getInt("retCode") + ")",
						Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private PhoneReceiver myReceiver2;
	private WifiManager mWifiManager;
	private WifiLock mWifiLock;
	private IntentFilter intentFilter;

	@Override
	public void onNext() {
		mDotView.selectNext();
	}

	@Override
	public void onPre() {
		mDotView.selectPre();
	}

	/**
	 * post请求
	 * 
	 * @author li Feb 4, 2015
	 */
	private void postDataToNe(String path, final String CardPassword,
			final String mPhone, final String Phone) {
		RequestQueue queue = Volley.newRequestQueue(this);
		StringRequest request = new StringRequest(Method.POST, http + path,
				new Listener<String>() {
					@Override
					public void onResponse(String response) {
						Log.i("LOL回拨内容", response);
						parserToObject(response);
					}
				}, new ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError arg0) {
						Log.i("LOG", "!!!!onErrorResponse：" + arg0.toString());
						Toast.makeText(getApplicationContext(), "呼叫失败，请稍后再试"+arg0.toString(), 0).show();
						finish();
						
						
						
					}
				}) {
			protected Map<String, String> getParams() throws AuthFailureError {
				String mp = encryptBASE64(mPhone);
				String p = encryptBASE64(Phone);
				Map<String, String> map = new HashMap<String, String>();
				map.put("Y2FsbGVy", mp);
				map.put("password", CardPassword);
				map.put("Y2FsbGVk", p);
				map.put("isShow", "1");
				map.put("appversion", getVersion());
				map.put("agentid", OEMID);
				map.put("proxyId", OEMID);
				return map;
			}
		};
		queue.add(request);
	}

	/**
	 * BASE64 加密
	 * 
	 * @param str
	 * @return
	 */
	public String encryptBASE64(String str) {
		if (str == null || str.length() == 0) {
			return null;
		}
		try {
			byte[] encode = str.getBytes("UTF-8");
			// base64 加密

			String s = new String(Base64.encode(encode, 0, encode.length,
					Base64.DEFAULT), "UTF-8");
			String s1 = s.replaceAll("=", "PQ");
			Log.i("LOL", s1);
			return s1;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return null;
	}

	private String getVersion() {
		try {
			// 得到包管理器
			PackageManager pm = getPackageManager();
			PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
			// 返回版本名
			String str = packageInfo.versionName.substring(0, 5);
			return str;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

	}

	/**
	 * 获取两个日期之间的间隔天数
	 * 
	 * @return
	 */
	public int getGapCount(long times) {
		/**
		 * 时间戳转换为日期对象
		 */
		Date date = new Date(times);
		Calendar fromCalendar = Calendar.getInstance();
		fromCalendar.setTime(date);
		fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
		fromCalendar.set(Calendar.MINUTE, 0);
		fromCalendar.set(Calendar.SECOND, 0);
		fromCalendar.set(Calendar.MILLISECOND, 0);

		Calendar toCalendar = Calendar.getInstance();
		toCalendar.setTime(new java.util.Date());
		toCalendar.set(Calendar.HOUR_OF_DAY, 0);
		toCalendar.set(Calendar.MINUTE, 0);
		toCalendar.set(Calendar.SECOND, 0);
		toCalendar.set(Calendar.MILLISECOND, 0);

		return (int) ((toCalendar.getTime().getTime() - fromCalendar.getTime()
				.getTime()) / (1000 * 60 * 60 * 24));
	}

	/**
	 * 查询姓名
	 * */
	public boolean queryNameInfo(Context context, String rawContactId)
			throws Exception {
		String names = "";
		try {

			Cursor cursorOfName = context.getContentResolver().query(
					Data.CONTENT_URI, // 查询data表
					new String[] { Data.DISPLAY_NAME,// 姓名
					}, Data.RAW_CONTACT_ID + " = ? ",
					new String[] { rawContactId }, null);

			while (cursorOfName.moveToNext()) {
				names = cursorOfName.getString(cursorOfName
						.getColumnIndex(Data.DISPLAY_NAME));
			}

		} catch (Exception e) {
			// TODO: handle exception
		}
		if (!TextUtils.isEmpty(names)
				&& names.equals(getResources().getString(R.string.app_name))) {
			return false;
		} else {
			return true;
		}

	}

}